package com.baizhi.controller;

import com.baizhi.common.Constant;
import com.baizhi.entity.Brand;
import com.baizhi.entity.ResultMap;
import com.baizhi.service.BrandService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("brand")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @RequestMapping("show")
    public ResultMap showBrand(String name,Integer page,Integer limit){
        ResultMap map = new ResultMap();
        PageInfo<Brand> pageInfo = brandService.selectByPage(name, page, limit);
        map.setCount(pageInfo.getTotal());
        map.setData(pageInfo.getList());
        return map;
    }
    @RequestMapping("upload")
    public Map upload(MultipartFile file){
        Map map = new HashMap();
        try {
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString()+oldName;
            file.transferTo(new File(Constant.IMG_LOCATION,newName));
            map.put("newFileName",newName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    @RequestMapping("add")
    public Map addBrand(Brand brand){
        Map map = new HashMap();
        try {
            brandService.insert(brand);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
        }
        return map;
    }
    @RequestMapping("delete")
    public Map deleteBrand(Integer id){
        Map map = new HashMap();
        try {
            brandService.delete(id);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
        }
        return map;
    }
    @RequestMapping("getOne")
    public Brand getOneBrand(Integer id){
        return brandService.selectById(id);
    }
    @RequestMapping("update")
    public Map updateBrand(Brand brand){
        Map map = new HashMap();
        try {
            brandService.update(brand);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
        }
        return map;
    }
}
